import React from 'react';
import { connect } from 'dva';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Tooltip, message } from 'antd';
import { InputNumberC, ModalC, NestedTableC } from '../../../../comps';
import ProductDetailContent from '../productDetail/productDetail';
import uuid from 'es6-uuid';
import moment from 'moment';

class ListTable extends React.Component {
  constructor() {
    super();
    this.state = {
      searchParams: {},
      expandRows: [],
      columns: [],
      tableList: [],
      disableArr: [], // 禁用
      selectedRowKeys: [], // 选择的row  keys
      selectedRowArr: [], // 选择的row数组对象
      childColumns: [],
      productDetail: false, // 产品明细弹窗
      layerTitle: '产品当日资金流水',
    };
  }

  componentDidMount() {
    this.props.onRef(this);
    this.setState(
      {
        searchParams: this.props.searchParams,
      },
      () => {
        this.getData();
      },
    );
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (JSON.stringify(nextProps.searchParams) != JSON.stringify(this.props.searchParams)) {
      this.setState(
        {
          searchParams: { ...this.state.searchParams, ...nextProps.searchParams },
        },
        () => {
          this.getData();
        },
      );
    }
  }

  getData = () => {
    const { searchParams } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'multiFundDivisionM/getList',
      payload: {
        productGroupId: searchParams?.productGroupId,
      },
      callback: (res) => {
        if (res) {
          this.setState({
            expandRows: res?.expandArr || [],
            columns: res?.columns || [],
            tableList: res?.tableList || [],
            disableArr: res?.disableArr || [],
            selectedRowKeys: res?.disableArr || [],
            selectedRowArr: res?.selectedArr || [],
            childColumns: res?.childColumns || [],
          });
        }
      },
    });
  };

  // 查看详情
  view = (record) => {
    const { selectedRowArr } = this.state;
    // 这边需要调用接口处理查看产品明细
    // 根据等级来推算出目前点击的这个里面 有哪些是需要的组合数组
    const params = selectedRowArr.filter((item) => {
      if (item.level.split('_').length > 2 && item.level.split('_')[1] == record.level.split('_')[1]) {
        return item.level.indexOf(record.level) == 0;
      }
    });
    this.setState(
      {
        productDetail: true,
        layerTitle: `${record.combName}当日资金流水`,
      },
      () => {
        const paramsArr = [];
        params.forEach((item) => {
          paramsArr.push(item.combId);
        });
        paramsArr.push(record.combId);
        const data = {
          combCodes: paramsArr,
          search_GTE_dataDt: moment().format('YYYYMMDD'),
          search_LTE_dataDt: moment().format('YYYYMMDD'),
          page: {
            current: 1,
            pageSize: 999999,
          },
          order: 'asc',
        };
        this.props.dispatch({
          type: 'capitalDetailsM/getSearch',
          payload: data,
        });
      },
    );
  };

  // 保存操作
  saveData = (record) => {
    const { tableList } = this.state;
    const newTableList = JSON.parse(JSON.stringify(tableList));
    if (!this.props.form.getFieldsValue().inputNumber && this.props.form.getFieldsValue().inputNumber != '0') {
      message.warning('真实余额未填写，不可保存！');
      return;
    }
    const cashActual = this.props.form.getFieldsValue().inputNumber;
    // 根据目前所在的record拿到key值，把TableList中这个数据改成保存的值，并且改变edit的状态
    const pos = record.key;
    newTableList.map((item) => {
      if (item.key == pos) {
        item.edit = false;
        item.actualRate = cashActual;
        item.dValue = item.totalrate - cashActual;
      }
    });
    this.setState(
      {
        tableList: newTableList,
      },
      () => {
        this.findParentBtnStatus();
      },
    );
  };

  // 编辑操作
  onEditItem = (record) => {
    const { tableList } = this.state;
    const newTableList = JSON.parse(JSON.stringify(tableList));
    const pos = record.key;
    newTableList.map((item) => {
      if (item.key == pos) {
        item.edit = true;
      }
    });
    this.setState(
      {
        tableList: newTableList,
      },
      () => {
        this.findParentBtnStatus();
      },
    );
  };

  // 取消操作
  cancelData = (record) => {
    const { tableList } = this.state;
    const newTableList = JSON.parse(JSON.stringify(tableList));
    if (newTableList && newTableList.length && !newTableList[0].actualRate) {
      message.warning('真实余额未填写，不可取消！');
      return;
    }
    const pos = record.key;
    newTableList.map((item) => {
      if (item.key == pos) {
        item.edit = false;
      }
    });
    this.setState(
      {
        tableList: newTableList,
      },
      () => {
        this.findParentBtnStatus();
      },
    );
  };

  // 内部改变父级的按钮状态
  findParentBtnStatus = () => {
    if (this.state.tableList.find((item) => item.edit)) {
      this.props._parentThis.setState({
        disabled: true,
      });
    } else {
      this.props._parentThis.setState({
        disabled: false,
      });
    }
  };

  // 供给外部调用获取所有选中的节点
  getTableSelect = () => {
    return this.state.selectedRowArr;
  };

  handleColumns = (columns) => {
    if (columns && columns.length) {
      if (columns[columns.length - 1].title != '操作') {
        columns.push({
          dataIndex: 'operate',
          key: 'operate',
          title: '操作',
          width: '20%',
          render: (text, record) => {
            if (record?.edit) {
              return (
                <>
                  <a onClick={() => this.saveData(record)}>保存</a>
                  <a onClick={() => this.cancelData(record)}>取消</a>
                </>
              );
            } else {
              return (
                <>
                  <a onClick={() => this.onEditItem(record)}>编辑</a>
                </>
              );
            }
          },
        });
      }
      columns.map((item) => {
        item.width = '20%';
        if (item.key == 'totalrate') {
          // 汇总现金余额
          item.align = 'right';
          item.type = 'money';
          item.title = (
            <div>
              <span style={{ marginRight: '8px' }}>汇总现金余额</span>
              <Tooltip title='汇总现金余额为子表中勾选的产品组合的现金余额总和' overlayClassName={'tableTipStyle'}>
                <QuestionCircleOutlined style={{ color: '#4D86FF' }} />
              </Tooltip>
            </div>
          );
        } else if (item.key == 'actualRate') {
          // 真实余额
          item.align = 'right';
          item.type = 'money';
          item.render = (text, record) => {
            if (record.edit) {
              return <InputNumberC title='' dataIndex='inputNumber' form={this.props.form} initialValue={text} precision={2} />;
            } else if (text || text == 0) {
              return <span>{this.changeRender(text)}</span>;
            } else {
              return '--';
            }
          };
        } else if (item.key == 'dValue') {
          // 差额
          item.align = 'right';
          item.type = 'money';
        }
      });
    }
  };

  // 选择的数组
  handleSelectedArr = () => {
    const { selectedRowArr, tableList } = this.state;
    if (selectedRowArr?.length) {
      const tableListNes = JSON.parse(JSON.stringify(tableList));
      let count = 0;
      selectedRowArr.forEach((item) => {
        count += Number(item.cashRate);
      });
      let compareValue;
      if (tableListNes[0].actualRate == null) {
        compareValue = null;
      } else {
        compareValue = count.toFixed(2) - tableListNes[0]?.actualRate;
      }
      tableListNes.map((items) => {
        items.totalrate = count.toFixed(2);
        items.dValue = compareValue;
      });
      return tableListNes;
    }
  };

  // 处理获取到的后台返回的数据
  handleDataSource = (res) => {
    const { expandRows, selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState(
          {
            selectedRowKeys,
            selectedRowArr: selectedRows,
          },
          () => {
            const newArrs = this.handleSelectedArr();
            this.setState({
              tableList: newArrs,
            });
          },
        );
      },
      getCheckboxProps: (record) => {
        return {
          disabled: this.state.disableArr.some((item) => item == record.key),
        };
      },
    };
    if (res && res.length) {
      res &&
        res.map((item, key) => {
          if (item.nestedConfig) {
            if (item.nestedConfig.columns && item.nestedConfig.columns.length) {
              const data_ = item.nestedConfig.columns;
              if (item.nestedConfig.columns[item.nestedConfig.columns.length - 1].title != '操作') {
                item.nestedConfig.columns.push({
                  dataIndex: 'operate',
                  key: 'operate',
                  title: '操作',
                  width: '300px',
                  render: (text, record) => {
                    if (this.state.disableArr.find((item) => item == record?.key)) {
                      return <a onClick={(e) => this.view(record)}> 详情 </a>;
                    } else {
                      return '';
                    }
                  },
                });
              } else {
                item.nestedConfig.columns[item.nestedConfig.columns.length - 1] = {
                  dataIndex: 'operate',
                  key: 'operate',
                  title: '操作',
                  width: '300px',
                  render: (text, record) => {
                    if (this.state.disableArr.find((item) => item == record?.key)) {
                      return <a onClick={(e) => this.view(record)}> 详情 </a>;
                    } else {
                      return '';
                    }
                  },
                };
              }
              for (let j = 0; j < data_.length; j++) {
                data_[j].width = '300px';
                if (data_[j].key == 'cashRate') {
                  data_[j].type = 'money';
                }
              }
            }
          }
          item.nestedConfig.rowSelection = rowSelection;
          item.nestedConfig.defaultExpandAllRows = true;
          // 子元素展开的key
          item.nestedConfig.expandedRowKeys = expandRows;
          item.nestedConfig.rowKey = 'key';
          // 子元素table的伸缩
          item.nestedConfig.onExpand = (expanded, record) => {
            let newArr = null;
            if (!expanded) {
              newArr = expandRows.filter((item) => item != record.key);
              this.setState({
                expandRows: newArr,
              });
            } else {
              expandRows.push(record.key);
              this.setState({
                expandRows,
              });
            }
          };
        });
      return res;
    }
  };

  // 父级元素的伸缩
  onExpand = (expanded, record) => {
    const { expandRows } = this.state;
    let newArr = null;
    if (!expanded) {
      newArr = expandRows.filter((item) => item != record.key);
      this.setState({
        expandRows: newArr,
      });
    } else {
      expandRows.push(record.key);
      this.setState({
        expandRows,
      });
    }
  };

  // 处理千分位
  changeRender = (text) => {
    const test = Number(text)
      .toFixed(2)
      .replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
    return test;
  };

  render() {
    const { columns, tableList, layerTitle } = this.state;
    const { loading } = this.props;
    const modalProps = {
      visible: this.state.productDetail,
      // confirmLoading:loading.effects['initialSplitM/uploadFile'] === true,
      title: layerTitle,
      onCancel: () => {
        this.setState({
          productDetail: false,
        });
      },
      width: 1200,
      footer: null,
    };
    this.handleDataSource(tableList);
    this.handleColumns(columns);
    return (
      <div style={{ marginTop: '12px' }}>
        <NestedTableC
          columns={columns}
          dataSource={tableList}
          rowKey='key'
          fixedChild={true}
          hidePage={true}
          loading={loading}
          commonHeader={false}
          defaultExpandAllRows={true}
          expandedRowKeys={this.state.expandRows}
          onExpand={this.onExpand}
        />
        <ModalC {...modalProps}>
          <ProductDetailContent />
        </ModalC>
      </div>
    );
  }
}
export default connect(({ multiFundDivisionM, capitalDetailsM, loading }) => ({ multiFundDivisionM, capitalDetailsM, loading: loading.effects['multiFundDivisionM/getList'] }))(
  Form.create()(ListTable),
);
